const app = getApp()
import { detail, poster } from '../../../api/goods'
import { toggle } from '../../../api/mine/like'
import { add } from '../../../api/cart'
import { getInfo } from '../../../utils/user'

Page({
  data: {
    back: true,
    title: '商品详细',
    loading: true,
    submitLoading: false,
    login: false, // 登录窗口
    share: false, // 分享窗口
    poster: false, // 海报窗口
    spec: false, // 规格选择窗口
    selectedSpecId: [], // 已选择的规格值ID数组
    posterEncode: '',
    detail: {},
    support: null,
    supportShow: false,
    info: {},
    like: false,
    cartTotal: 0,
    // ----
    height: 64, // header高度
    scrollHeight: 0, // 滚动总高度
    top: 0, // 标题图标距离顶部距离
    opcity: 0,
    iconOpcity: 0.5,
    bannerIndex: 0,
    form: {
      goods_id: 0,
      goods_name: '',
      subtitle: '',
      image: '',
      goods_sku_id: 0,
      sku_name: '',
      sales_price: 0,
      quantity: 1,
      stock: 0
    },
    abnor: {
      title: '这个商品已经下线了，再看看其他的吧~',
      button: ''
    }
  },
  onLoad (options) {
    this.setData({
      loading: true,
      info: getInfo
    })
    this.setHeader()
    detail(options.id).then(res => {
      const detail = res.data.detail
      detail.content = detail.content.replace(/<img/gi, '<img style="max-width:100%;height:auto;float:left;display:block" ')

      const form = this.data.form
      form.goods_id = detail.id
      form.goods_name = detail.goods_name
      form.subtitle = detail.subtitle
      form.image = detail.image
      form.sku_type = detail.sku_type
      form.sales_price = detail.sales_price
      form.sku_name = ''
      form.stock = detail.stock
      form.quantity = detail.min_quantity
      form.goods_sku_id = detail.sku_type == 10 ? detail.sku[0].id : 0
      this.setData({
        detail: detail,
        support: detail.support,
        like: res.data.like,
        cartTotal: res.data.cart,
        form: form
      })
    })
      .catch(e => {
        this.setData({ detail: null })
      })
      .finally(() => {
        this.setData({ loading: false })
      })
  },
  onShow () {},
  onPageScroll (event) {
    const scroll = event.scrollTop <= 0 ? 0 : event.scrollTop
    const opcity = scroll / this.data.scrollHeight
    if (this.data.opcity >= 1 && opcity >= 1) {
      return
    }
    this.setData({
      opcity: opcity,
      iconOpcity: 0.5 * (1 - opcity < 0 ? 0 : 1 - opcity)
    })
  },
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () { /* 页面上拉触底事件的处理函数*/ },
  onShareAppMessage (event) {
    return {
      path: '/pages/index/index?share=goods&id=' + this.data.form.goods_id
    }
  },

  // ===================method================//

  setHeader () {
    const menu = wx.getMenuButtonBoundingClientRect()
    this.setData({
      width: menu.left,
      height: menu.top + menu.height + 8,
      top: menu.top + (menu.height - 32) / 2
    }, () => {
      wx.getSystemInfo({
        success: (res) => {
          this.setData({
            scrollHeight: res.windowWidth
          })
        }
      })
    })
  },
  bannerChange: function (event) {
    this.setData({
      bannerIndex: event.detail.current
    })
  },
  // 收藏
  like () {
    if (app.login()) {
      toggle(this.data.form.goods_id).then()
        .finally(() => {
          this.setData({
            like: !this.data.like
          })
        })
    } else {
      this.setData({ login: true })
    }
  },
  // 预览图片
  previewImage (event) {
    const current = event.currentTarget.dataset.url
    const images = []
    this.data.detail.images.forEach(item => {
      images.push(item.url)
    })
    wx.previewImage({
      current: current,
      urls: images
    })
  },
  // 隐藏规格选择区
  specClose () {
    this.setData({ spec: false })
  },
  // 打开规格选择窗
  openSpec () {
    if (!this.data.spec) {
      this.setData({ spec: true })
    }
  },
  /**
   * 检查当前选择的sku库存是否充足
   */
  checkStock (id) {
    let stock = 0
    this.data.detail.sku.forEach(item => {
      if (item.id == id) {
        stock = item.stock
      }
    })
    return stock >= this.data.form.quantity
  },
  openSpec (event) {
    this.setData({ spec: true })
  },
  cart () {
    if (app.login()) {
      if (this.data.form.goods_sku_id == 0) {
        app.toast('请选择商品规格')
        return false
      }
      if (!this.checkStock(this.data.form.goods_sku_id)) {
        app.toast('该商品库存不足')
        return false
      }
      
      this.setData({ submitLoading: true })
      add(this.data.form).then(res => {
        app.toast(res.msg, '', 'success')
        this.setData({ cartTotal: parseInt(this.data.cartTotal) + parseInt(this.data.form.quantity) })
      })
        .catch(e => {
          app.toast(e.msg)
        })
        .finally(() => {
          this.setData({ submitLoading: false, spec: false })
        })
    } else {
      this.setData({ login: true })
    }
  },
  buy () {
    if (app.login()) {
      if (this.data.form.goods_sku_id == 0) {
        app.toast('请选择商品规格')
        return false
      }
      if (!this.checkStock(this.data.form.goods_sku_id)) {
        app.toast('该商品库存不足')
        return false
      }

      const sku = []
      sku.push({
        id: this.data.form.goods_sku_id,
        quantity: this.data.form.quantity
      })
      wx.setStorageSync('sku', sku)
      this.setData({ spec: false })
      app.redirect('/pages/order/confirm/index')
    } else {
      this.setData({ login: true })
    }
  },
  /**
   * 处理选择规格
   */
  specSelect (event) {
    const selectedSpecId = this.data.selectedSpecId
    const id = event.currentTarget.dataset.id
    const name = event.currentTarget.dataset.name
    const index = event.currentTarget.dataset.index
    selectedSpecId[index] = id
    // 判断规格是否已全部选择了
    if (this.data.detail.spec.length == selectedSpecId.length) {
      this.setSku()
    }
    this.setData({ selectedSpecId: selectedSpecId })
  },
  /**
   * 规格已全部选择
   */
  setSku () {
    const form = this.data.form
    const sku_no = this.data.selectedSpecId.join(':')
    this.data.detail.sku.forEach(item => {
      if (item.sku_no == sku_no) {
        form.goods_sku_id = item.id
        form.sku_name = item.sku_name
        form.sales_price = item.sales_price
        form.stock = item.stock
        form.image = item.image != '' ? item.image : form.image
        this.setData({ form: form })
      }
    })
  },
  /**
   * 改变购买数量
   */
  quantityChange (event) {
    const form = this.data.form
    form.quantity = event.detail
    this.setData({ form: form })
  },
  // 打开分享弹出框
  share () {
    this.setData({ share: true })
  },
  // 生成海报
  onMakePoser (e) {
    this.setData({ share: false })
    wx.showLoading({ title: '加载中...' })
    poster(this.data.form.goods_id).then(res => {
      this.setData({
        posterEncode: res.data.encode,
        poster: true
      })
    })
      .finally(() => {
        wx.hideLoading()
      })
  },
  // 打开支持弹出框
  openSupport () {
    this.setData({ supportShow: true })
  },
  // 关闭支持弹出框
  closeSupport () {
    this.setData({ supportShow: false })
  },
  goHome () {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  goCart () {
    wx.navigateTo({
      url: '/pages/cart/index'
    })
  },
  goBack: function () {
    wx.navigateBack()
  },
  redirect (event) {
    app.redirect(event.currentTarget.dataset.url)
  }
})